# data/skill.py
import random

class Skill:
    def __init__(self, name, skill_type, power, accuracy, max_pp,use_mp, effect=None):
        self.name = name
        self.type = skill_type
        self.power = power
        self.accuracy = accuracy
        self.max_pp = max_pp
        self.current_pp = max_pp
        self.use_mp = use_mp
        self.effect = effect
        
    def use(self, user, target):
        if self.current_pp <= 0:
            return False, f"{self.name} pp ues out!"
        
        self.current_pp -= 1
        
        if random.randint(1, 100) > self.accuracy:
            return False, f"{user.name} : {self.name} miss!"
        
        damage = self.calculate_damage(user, target)
        target.take_damage(damage)
        
        effect_msg = ""
        if self.effect:
            effect_msg = self.effect(user, target)
        
        type_msg = self.get_type_message(self.type, target.attribute)
        success_msg = f"{user.name} use {self.name}!{type_msg}cause {damage} damage!" + effect_msg
        return True, success_msg
    
    def calculate_damage(self, user, target):
        from .attribute_restraint import Attribute
        
        attack = user.attack
        defense = target.defence
        try:
            if type(target.attribute) == list:
                raise ValueError(f"target attribute is list")
        except ValueError as e:
            print(e)
        type_multiplier = Attribute.get_restraint_multiplier(
            self.type,  target.attribute
        )
        
        random_factor = 0.85 + 0.15 * random.random()
        critical = 1.5 if random.random() < 0.0625 else 1.0
        
        damage = (( self.power * attack / defense) / 50 + 2)
        damage *= type_multiplier * random_factor * critical
        
        return int(max(1, damage))
    
    def get_type_message(self, attack_type, defense_types):
        from .attribute_restraint import Attribute
        multiplier = Attribute.get_restraint_multiplier(attack_type, defense_types)
        
        if multiplier >= 2:
            return "effective! "
        elif multiplier <= 0.5:
            return "not very effective... "
        elif multiplier == 0:
            return "no effect! "
        return ""
    
    def __str__(self):
        return f"{self.name} [{self.type}] power:{self.power} pp:{self.pp}/{self.max_pp}"
